package casia.isiteam.springbootshiro.service.user;

import casia.isiteam.springbootshiro.model.po.common.IpInfo;
import casia.isiteam.springbootshiro.model.po.common.IpInfoRepository;
import casia.isiteam.springbootshiro.model.po.common.UserInfo;
import casia.isiteam.springbootshiro.model.po.common.UserInfoRepository;
import casia.isiteam.springbootshiro.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Author wzy
 * Date 2018/1/15 14:46
 */
@Service
public class UserInfoService {
    @Resource
    private UserInfoRepository userInfoRepository;
    @Autowired
    private IpInfoRepository ipInfoRepository;

    public UserInfo findByUsername(String username) {
        UserInfo userInfo = userInfoRepository.findByUsername(username);
        return userInfo;
    }
    public List<UserInfo> findAllByDepIdAndRole(int dep_id, int role, Pageable pageable) throws Exception{
        List<UserInfo> list = userInfoRepository.findAllByDepIdAndRoleAndInstIdNot( dep_id , role ,-1 , pageable);
        for( UserInfo userInfo:list ){
            userInfo.setPassword(null);
        }
        return  list;
    }
    public List<UserInfo> findAllInvalidUser() throws Exception{
        List<UserInfo> list =  userInfoRepository.queryAllInvalidUsers( new Date() ,0);
        for( UserInfo userInfo:list ){
            userInfo.setPassword(null);
        }
        return list;
    }

    /**
     * 保存登录用户ip
     * @param ip
     * @param user_id
     * @return
     */
    @Transactional(value = "transactionManagerCommon",rollbackFor=Exception.class) //开启事务
    public void saveIp(String ip,int user_id) throws Exception{
        IpInfo ipInfo = new IpInfo();
        ipInfo.setIp(ip);
        ipInfo.setUserId(user_id);
        ipInfoRepository.save(ipInfo);
    }

    /**
     * 查询用户登录ip
     * @param user_id
     * @param page
     * @param size
     * @return
     */
    public List<IpInfo> searchUserLoginIp(int user_id,int page,int size) throws Exception{
        Sort sort= new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page,size,sort);
        return ipInfoRepository.findByUserId(user_id,pageable);
    }
}
